//
//  ST_PeculiaritySquareController.swift
//  btvideo
//
//  Created by mac on 2020/1/14.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import MJRefresh
import SwifterSwift
import SwiftyUserDefaults

//特质广场-Controller
class ST_PeculiaritySquareController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
        }
        
        binding()
        
    }
    private func binding(){
        
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            self.request_data()
        })
        
        
        SCComponets.login_status_did_changed_observable().distinctUntilChanged().withUnretained(self).subscribe(onNext: { own,f in
            print("SCComponets.login_status_did_changed_observable()")
            if f == true{
                own.request_data()
            }else{
                
                own.viewModel = ST_PeculiaritySquareViewModel()
                own.collectionView.reloadData()
            }
            
        }).disposed(by: rx.disposeBag)
        
        
    }
    //    MARk: - scan UI
    fileprivate func stop_scan_view(){
        
        scan_root_view.isHidden = true
        scan_animate_view.stop()
        
    }
    
    fileprivate func play_scan_view(){
        
        if scan_root_view.superview == nil{
            view.insertSubview(scan_root_view, aboveSubview: collectionView)
            scan_root_view.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            
            
            scan_root_view.addSubview(scan_animate_view)
            scan_animate_view.snp.makeConstraints { (make) in
                make.width.height.equalTo(50/375.0*ScreenWidth)
                make.centerX.equalToSuperview()
                make.centerY.equalToSuperview()
            }
        }
        scan_root_view.isHidden = false
        scan_animate_view.play()
    }
    
    
    
    fileprivate lazy var scan_root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.white
        return control
    }()
    
    fileprivate lazy var scan_animate_view:LOTAnimationView = {
        
        let path = Bundle.main.path(forResource: "homeSearchAnimation", ofType: "json")!
        
        let control = LOTAnimationView.init(filePath: path)
        
        control.contentMode = UIView.ContentMode.scaleAspectFill
        
        control.loopAnimation = true
        
        return control
    }()
    
    //     MARK: - Properties
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.headerReferenceSize = CGSize.init(width: ScreenWidth, height: ST_PecSquareHeaderView.height)
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.sectionInset = UIEdgeInsets.init(top: 30, left: 0, bottom: BTSafeAreaBottom + 49, right: 0)
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        
        control.register(cellWithClass: ST_PecSqureFantasticUpdateCell.self)
        control.register(cellWithClass: ST_PecSqureHotCell.self)
        
        
        control.register(cellWithClass: ST_PecSquareSectionCell.self)
        control.register(cellWithClass: ST_PecSquareTabCell.self)
        control.register(cellWithClass: ST_PecSquareNormalLeftCell.self)
        control.register(cellWithClass: ST_PecSquareNormalRightCell.self)
        control.register(cellWithClass: ST_PecSquareBestLoveSectionCell.self)
        
        
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_PecSquareHeaderView.self)
        
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate var viewModel = ST_PeculiaritySquareViewModel()
    
    
    
    //     MARK: - request_data
    
    @objc func request_data(){
        
        play_scan_view()
        
        JVrequest(PH.PeculiaritySquareApi, success: { (json) in
            
            print("当前返回的 特质广场：",json)
            
            self.stop_scan_view()
            
            self.viewModel.create_view_model(json: json["data"])
            
            self.collectionView.reloadData {
                self.collectionView.mj_header?.endRefreshing()
            }
            
        }) { (code, err) in
            
            self.collectionView.mj_header?.endRefreshing()
            
            ToastHud(text: err, view: self.view)
        }
        
        
    }
    
}


extension ST_PeculiaritySquareController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_PecSquareHeaderView.self, for: indexPath)
        
        view.array = viewModel.header_array
        
        return view
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let model = viewModel.data_array[indexPath.item]
        
        
        if let m = model as? ST_PeculiaritySquareCollectionCellModel {
            
            if m.cellType == .normalSection{
                let cell = collectionView.dequeueReusableCell(withClass: ST_PecSquareSectionCell.self, for: indexPath)
                
                cell.model = m
                
                return cell
                
            }else{
                
                let cell = collectionView.dequeueReusableCell(withClass: ST_PecSquareBestLoveSectionCell.self, for: indexPath)
                
                cell.model = m
                
                return cell
            }
            
            
        }else if let m = model as? ST_PeculiaritySquareTabCellModel {
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_PecSquareTabCell.self, for: indexPath)
            
            cell.model = m
            
            cell.click_closure = {[weak self] tag in
                
                //                self?.viewModel.switch_last_array(tag: tag)
                
                //                self?.collectionView.reloadData()
                
                guard let strongSelf = self else { return }
                
                let startIdx = strongSelf.viewModel.data_array.firstIndex(where: {$0 is ST_PeculiaritySquareNormalCellModel})?.uInt
                
                guard let uIdx = startIdx else { return }
                
                let idx = Int(uIdx-1)
                
                let beforeRange = Array(idx...strongSelf.viewModel.data_array.count-1)
                
                strongSelf.viewModel.switch_last_array(tag: tag)
                
                let afterRange = Array(idx...strongSelf.viewModel.data_array.count-1)
                
                strongSelf.collectionView.performBatchUpdates({
                    
                    let deleteIndexPaths = beforeRange.map { IndexPath(item: $0, section: 0) }
                    
                    collectionView.deleteItems(at: deleteIndexPaths)
                    
                    let insertIndexPaths = afterRange.map { IndexPath(item: $0, section: 0) }
                    
                    collectionView.insertItems(at: insertIndexPaths)
                    
                }) { (f) in
                    
                    print("切换 显示 完毕")
                    
                }
                
                
            }
            
            return cell
            
            
        }else{
            
            if indexPath.row%2 != 0{
                
                let cell = collectionView.dequeueReusableCell(withClass:ST_PecSquareNormalLeftCell.self, for: indexPath)
                
                if let m = model as? ST_PeculiaritySquareNormalCellModel {
                    cell.model = m
                }
                return cell
            }
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_PecSquareNormalRightCell.self, for: indexPath)
            
            if let m = model as? ST_PeculiaritySquareNormalCellModel {
                cell.model = m
            }
            return cell
            
        }
        
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return viewModel.data_array[indexPath.item].cellSize
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if let m = viewModel.data_array[indexPath.item] as? ST_PeculiaritySquareNormalCellModel {
            
            
            let vc = ST_PeculiarityTypeListController()
            
            vc.peculiarity_id = m.pec.id.string
            
            self.navigationController?.pushViewController(vc)
        }
        
    }
    
    
    
}
